package org.exez.modules.visitor.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.exez.common.api.vo.Result;
import org.exez.common.aspect.annotation.AutoLog;
import org.exez.common.system.base.controller.JeecgController;
import org.exez.common.system.vo.LoginUser;
import org.exez.common.util.IPUtils;
import org.exez.modules.system.entity.SysLog;
import org.exez.modules.system.service.ISysLogService;
import org.exez.modules.system.service.ISysUserService;
import org.exez.modules.visitor.constant.AuthorityEnum;
import org.exez.modules.visitor.constant.Enum;
import org.exez.modules.visitor.entity.VisitorAccessre;
import org.exez.modules.visitor.entity.WhiteList;
import org.exez.modules.visitor.service.IWhiteListService;
import org.exez.modules.visitor.service.SjyService;
import org.exez.modules.visitor.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 白名单
 * @Author: exez-boot
 * @Date: 2020-06-27
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "白名单")
@RestController
@RequestMapping("/visitor/whiteList")
public class WhiteListController extends JeecgController<WhiteList, IWhiteListService> {
    @Autowired
    private IWhiteListService whiteListService;


    @Autowired
    private ISysLogService sysLogService;

    @Autowired
    private SjyService sjyService;

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "白名单-分页列表查询")
    @ApiOperation(value = "白名单-分页列表查询", notes = "白名单-分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "whiteName", value = "姓名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "whiteMobile", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "institutionId", value = "单位id", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页码大小", required = true, dataType = "Integer", paramType = "query"),
    })
    @GetMapping(value = "/list")
    public Result<IPage<WhiteListVO>> queryPageList(@RequestParam(name = "whiteName", required = false) String whiteName,
                                                    @RequestParam(name = "whiteMobile", required = false) String whiteMobile,
                                                    @RequestParam(name = "institutionId", required = false) Integer institutionId,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<WhiteListVO>> result = new Result<>();
        LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper<>();

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        if (null != institutionId) {
            queryWrapper.eq(WhiteList::getInstitutionId, institutionId);
        }else if (!AuthorityEnum.ONE_USER.getIndex().equals(sysUser.getAuthority())) {
            queryWrapper.eq(WhiteList::getInstitutionId, sysUser.getInstitutionId());
        }


        if (StringUtils.isNotBlank(whiteName)) {
            queryWrapper.like(WhiteList::getWhiteName, whiteName);
        }
        if (StringUtils.isNotBlank(whiteMobile)) {
            queryWrapper.like(WhiteList::getWhiteMobile, whiteMobile);
        }

        queryWrapper.eq(WhiteList::getDeleted, 1);
        queryWrapper.orderByDesc(WhiteList::getId);
        Page<WhiteList> page = new Page<WhiteList>(pageNo, pageSize);

        IPage<WhiteListVO> whiteListVOIPage = whiteListService.listWhiteList(page, queryWrapper);
        result.successSetDate(whiteListVOIPage);
        return result;
    }

    /**
     * 添加
     *
     * @param whiteListSaveVO
     * @return
     */
    @AutoLog(value = "白名单-添加", logType = 3, operateType = 2)
    @ApiOperation(value = "白名单-添加", notes = "白名单-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@Validated @RequestBody WhiteListSaveVO whiteListSaveVO) {

        WhiteList whiteList = new WhiteList();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        BeanUtils.copyProperties(whiteListSaveVO,whiteList);
        whiteList.setInstitutionId(Integer.parseInt(sysUser.getInstitutionId()));
        whiteList.setCreateBy(sysUser.getId());
        whiteList.setUpdateBy(sysUser.getId());

        whiteListService.saveWhiteList(whiteList);

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param whiteListUpdateVO
     * @return
     */
    @AutoLog(value = "白名单-编辑", logType = 3, operateType = 3)
    @ApiOperation(value = "白名单-编辑", notes = "白名单-编辑")
    @PostMapping(value = "/edit")
    public Result<String> edit(@RequestBody WhiteListUpdateVO whiteListUpdateVO) {
        WhiteList entity = new WhiteList();
        BeanUtils.copyProperties(whiteListUpdateVO,entity);
        whiteListService.updateWhiteList(entity);

        return Result.ok("编辑成功!");
    }

    /**
     * 批量同步没有头像的数据
     *
     * @param
     * @return
     */
    @AutoLog(value = "批量同步白名单-编辑", logType = 3, operateType = 3)
    @ApiOperation(value = "批量同步白名单-编辑", notes = "批量同步白名单-编辑")
    @GetMapping(value = "/batchSyncWhiteList")
    public Result<String> batchSyncWhiteList() {

        whiteListService.batchSyncWhiteList();

        return Result.ok("同步成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "白名单-通过id删除", logType = 3, operateType = 4)
    @ApiOperation(value = "白名单-通过id删除", notes = "白名单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) Integer id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        WhiteList whiteList = new WhiteList();
        whiteList.setId(id);
        whiteList.setUpdateBy(sysUser.getId());
        whiteList.setDeleted(0);
        whiteList.setUpdateTime(new Date());

        List<WhiteList> whiteLists = new ArrayList();
        whiteLists.add(whiteList);
        whiteListService.deletedWhiteList(whiteLists);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "白名单-批量删除", logType = 3, operateType = 4)
    @ApiOperation(value = "白名单-批量删除,逗号隔开", notes = "白名单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "id", required = true) String id) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        String[] split = id.split(",");

        List<WhiteList> whiteLists = new ArrayList();
        for (String string : split) {
            WhiteList whiteList = new WhiteList();
            whiteList.setId(Integer.parseInt(string));
            whiteList.setUpdateBy(sysUser.getId());
            whiteList.setDeleted(0);
            whiteList.setUpdateTime(new Date());
            whiteLists.add(whiteList);
        }

        this.whiteListService.deletedWhiteList(whiteLists);

        return Result.ok("批量删除成功！");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "白名单-通过id查询")
    @ApiOperation(value = "白名单-通过id查询", notes = "白名单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WhiteListVO> queryById(@RequestParam(name = "id", required = true) Integer id) {
        Result<WhiteListVO> result = new Result<>();

        WhiteListVO whiteListById = whiteListService.getWhiteListById(id);
        result.successSetDate(whiteListById);
        return result;
    }


    /**
     * 通过excel导入数据
     *
     * @param
     * @param
     * @return
     */

    @ApiOperation(value = "excl导入", notes = "excl导入")
    @RequestMapping(value = "/imPortExcl", method = RequestMethod.POST)
    public Result<?> imPortExcl(@RequestParam(value = "file") MultipartFile file) {
        Result<List<Integer>> result = new Result<>();
        try {
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            if (substring.equals("xls") || substring.equals("xlsx") || substring.equals("XLS") || substring.equals("XLSX")) {

            } else {
                result.setMessage("文件格式只支持excl表格！");
                result.setCode(-1);
                return result;
            }
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<WhiteListVOExcl> whiteLists = reader.readAll(WhiteListVOExcl.class);
            if (whiteLists.size() > 10000) {
                result.setMessage("每次最多支持导入10000条数据！");
                result.setCode(-1);
                return result;
            }
            List<Integer> whiteLists1 = whiteListService.imPortExcl(whiteLists);
            int i = whiteLists.size() - whiteLists1.size();
            result.setMessage("已导入成功" + i + "条数据！");
            result.successSetDate(whiteLists1);

            saveLog("白名单导入",5);
        } catch (Exception e) {
            result.setMessage("数据错误！");
        }

        return result;
    }


    /**
     * 通过excel导入数据
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "excl导入测试啊啊啊啊啊啊", notes = "excl导入测试啊啊啊啊啊啊")
    @RequestMapping(value = "/imPortExclTest", method = RequestMethod.POST)
    public Result<?> imPortExclTest(@RequestParam(value = "file") MultipartFile file) {
        Result<List<Integer>> result = new Result<>();
        try {
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            if (substring.equals("xls") || substring.equals("xlsx") || substring.equals("XLS") || substring.equals("XLSX")) {

            } else {
                result.setMessage("文件格式只支持excl表格！");
                result.setCode(-1);
                return result;
            }
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<WhiteListVOExcl> whiteLists = reader.readAll(WhiteListVOExcl.class);
            if (whiteLists.size() > 10000) {
                result.setMessage("每次最多支持导入10000条数据！");
                result.setCode(-1);
                return result;
            }
            List<Integer> whiteLists1 = whiteListService.imPortExclTest(whiteLists);
            int i = whiteLists.size() - whiteLists1.size();
            result.setMessage("已导入成功" + i + "条数据！");
            result.successSetDate(whiteLists1);
        } catch (Exception e) {
            result.setMessage("数据错误！");
        }

        return result;
    }

    /**
     * 白名单导入图片
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "白名单导入图片", notes = "白名单导入图片")
    @RequestMapping(value = "/imPortPhoto", method = RequestMethod.POST)
    public Result<?> imPortPhoto(@RequestParam(value = "file") MultipartFile file, String hash,String name ,HttpServletResponse response, HttpServletRequest request) {
        Result<List<Integer>> result = new Result<>();
        try {
            System.out.println("进入了Controller层！！！！！！！！！！！！！！！！！！！");

            /*MultipartFileParam param = new MultipartFileParam();
            param.setTaskId(name);
            param.setChunk(Integer.parseInt(hash.substring(0,hash.indexOf("/"))));
            param.setChunkTotal(Integer.parseInt(hash.substring(hash.indexOf("/")+1)));
            param.setSize(5*1024*1024);
            param.setFile(file);
            whiteListService.chunkUploadByMappedByteBuffer(param);*/

            MultipartFileParams param = new MultipartFileParams();
            param.setFile(file);
            param.setChunkNumber(Integer.parseInt(hash.substring(0,hash.indexOf("/"))));
            param.setTotalChunks(Integer.parseInt(hash.substring(hash.indexOf("/")+1)));
            param.setChunkSize(5*1024*1024);
            param.setIdentifier("123456");
            param.setTaskId("123456788888");
            whiteListService.chunkUploadByMappedByteBuffer1(param,name);//service层

            saveLog("白名单导入图片",5);
        } catch (Exception e) {
            result.setMessage("数据错误！");
        }

        return result;
    }

    private void saveLog(String logContent,Integer operateType) {
        SysLog sysLog = new SysLog();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sysLog.setCreateBy(sysUser.getUsername());
        sysLog.setCreateTime(new Date());
        sysLog.setUpdateBy(sysUser.getUsername());
        sysLog.setUpdateTime(new Date());
        sysLog.setUsername(sysUser.getUsername());
        sysLog.setUserid(sysUser.getId());
        sysLog.setLogContent(logContent);
        sysLog.setKeyInformation(logContent);
        sysLog.setLogType(3);
        sysLog.setOperateType(operateType);
        sysLog.setInstitutionId(Integer.parseInt(sysUser.getInstitutionId()));

        sysLogService.save(sysLog);
    }

    /**
     * 描述：下载外部案件导入模板
     * @param response
     * @param request
     * @author songfayuan
     * 2018年6月7日下午5:03:59
     */
    @ResponseBody
    @ApiOperation(value = "白名单模板下载", notes = "白名单模板下载啊")
    @GetMapping("/download")   //此处尽量get请求,post不知为何有问题
    public void downloadExcel(HttpServletResponse response,HttpServletRequest request) {
        //方法一：可以采用POI导出excel，但是比较麻烦
		try {
			Workbook workbook = new HSSFWorkbook();
			request.setCharacterEncoding("UTF-8");
	        response.setCharacterEncoding("UTF-8");
	        response.setContentType("application/x-download");


	        String filedisplay = "白名单模板.xls";

	        filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
	        response.addHeader("Content-Disposition", "attachment;filename="+ filedisplay);

			// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
			Sheet sheet = workbook.createSheet("白名单模板");
			// 第三步，在sheet中添加表头第0行
			Row row = sheet.createRow(0);
			// 第四步，创建单元格，并设置值表头 设置表头居中
			CellStyle style = workbook.createCellStyle();
	        //style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式

			Cell cell = row.createCell(0);
	        cell.setCellValue("姓名");
	        cell.setCellStyle(style);
	        sheet.setColumnWidth(0, (25 * 256));  //设置列宽，50个字符宽

	        cell = row.createCell(1);
	        cell.setCellValue("手机号码");
	        cell.setCellStyle(style);
	        sheet.setColumnWidth(1, (20 * 256));  //设置列宽，50个字符宽

	        cell = row.createCell(2);
	        cell.setCellValue("证件类型1身份证2护照");
	        cell.setCellStyle(style);
	        sheet.setColumnWidth(2, (15 * 400));  //设置列宽，50个字符宽

	        cell = row.createCell(3);
	        cell.setCellValue("证件号码");
	        cell.setCellStyle(style);
	        sheet.setColumnWidth(3, (15 * 600));  //设置列宽，50个字符宽

            cell = row.createCell(4);
            cell.setCellValue("工作证号");
            cell.setCellStyle(style);
            sheet.setColumnWidth(4, (15 * 300));  //设置列宽，50个字符宽

            cell = row.createCell(5);
            cell.setCellValue("车牌号");
            cell.setCellStyle(style);
            sheet.setColumnWidth(5, (15 * 600));  //设置列宽，50个字符宽

	        // 第五步，写入实体数据 实际应用中这些数据从数据库得到
			row = sheet.createRow(1);
			row.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("张三");
			row.createCell(1, Cell.CELL_TYPE_STRING).setCellValue("15232321111");
			row.createCell(2, Cell.CELL_TYPE_STRING).setCellValue("1");   //商品价格
			row.createCell(3, Cell.CELL_TYPE_STRING).setCellValue("341023198236326079");  //规格
            row.createCell(4, Cell.CELL_TYPE_STRING).setCellValue("123");  //规格
            row.createCell(5, Cell.CELL_TYPE_STRING).setCellValue("浙B9W9W1");  //规格

            row = sheet.createRow(2);
            row.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("李四");
            row.createCell(1, Cell.CELL_TYPE_STRING).setCellValue("15232323333");
            row.createCell(2, Cell.CELL_TYPE_STRING).setCellValue("2");   //商品价格
            row.createCell(3, Cell.CELL_TYPE_STRING).setCellValue("G81029963");  //规格
            row.createCell(4, Cell.CELL_TYPE_STRING).setCellValue("123");  //规格
            row.createCell(5, Cell.CELL_TYPE_STRING).setCellValue("浙B9W9W1,浙B9W9W2");  //规格
			// 第六步，将文件存到指定位置
	        try
	        {
	        	OutputStream out = response.getOutputStream();
	        	workbook.write(out);
	            out.close();
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
